package br.com.carser.filter;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 * Filter to open session in request.
 * 
 * @author Eduardo T. Serete
 */
//@WebFilter(servletNames={"Faces Servlet"})
public class HibernateSessionRequestFilter implements Filter {

	@Resource
	private UserTransaction transaction;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) {
		
		try {
			transaction.begin();
			chain.doFilter(request, response);
			transaction.commit();
		} catch (Exception e) {
			try {
				transaction.rollback();
			} catch (IllegalStateException | SecurityException
					| SystemException e1) {
				e1.printStackTrace();
			}
		} finally {
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}
}
